<template>
  <div class="container">
    <h4>
      <el-button type="danger" size="mini" @click="exportJson" >导出GeoJSON</el-button>
    </h4>
    <div id="vue-openlayers"></div>
  </div>
</template>

<script>
import 'ol/ol.css'
import { Map, View } from 'ol'
import { Tile } from 'ol/layer'
import { XYZ } from 'ol/source'
import SourceVector from 'ol/source/Vector' // 矢量数据源
import VectorLayer from 'ol/layer/Vector' // 矢量图层
const FileSaver = require('file-saver')
export default {
  data() {
    return {
      map: null,
      source: new SourceVector({
        wrapX: false // 禁止地图在水平方向上无限滚动
      }),
      view: new View({
        projection: 'EPSG:4326',
        center: [8.2275, 6.8185], // 中心点
        zoom: 3
      })
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMap() {
      this.map = new Map({
        target: 'vue-openlayers',
        layers: [
          new Tile({
            source: new XYZ({
              url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7'
            })
          })
        ],
        view: this.view
      })
    },

    exportJson() {
      let feadata = {
        type: 'FeatureCollection', // FeatureCollection 代表一个要素集合
        features: [
          {
            type: 'Feature', // Feature 代表一个要素
            geometry: {
              type: 'Point', // Point 代表一个点
              coordinates: [102.0, 0.5] // 坐标
            }
          },
          {
            type: 'Feature',
            geometry: {
              type: 'LineString', // LineString 代表一条线
              coordinates: [
                [102.0, 0.0],
                [103.0, 1.0],
                [104.0, 0.0],
                [105.0, 1.0]
              ]
            },
            properties: { // 属性 用于存储一些信息
              prop0: 'value0',
              prop1: 0.0
            }
          },
          {
            type: 'Feature',
            geometry: {
              type: 'Polygon', // Polygon 代表一个多边形
              coordinates: [
                [
                  [100.0, 0.0],
                  [101.0, 0.0],
                  [101.0, 1.0],
                  [100.0, 1.0],
                  [100.0, 0.0]
                ]
              ]
            },
            properties: {
              prop0: 'value0',
              prop1: { this: 'that' }
            }
          }
        ]
      }
      const content = JSON.stringify(feadata)
      const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
      FileSaver.saveAs(blob, 'data.json')
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
    width: 840px;
    height: 550px;
    margin: 50px auto;
    border: 1px solid #ccc;
    #vue-openlayers {
      width: 800px;
      height: 420px;
      margin: 0 auto;
      border: 1px solid #42b983;
      position: relative;
    }
  }
</style>